/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.typhosoft.photohz2o.server;

import com.esotericsoftware.kryonet.Connection;
import com.typhosoft.jcommon.bean.CPhoto;
import com.typhosoft.jcommon.network.CSendActivity;
import com.typhosoft.jcommon.network.CServer;
import com.typhosoft.jcommon.photo.CPathProvider;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author SantonocitoM
 */
public class Main extends Thread {

    private final CPhotoConsumer fPhotoConsumer;
    private final CLogInConsumer fLogInConsumer;

    public Main() throws IOException, URISyntaxException {
        fPhotoConsumer = new CPhotoConsumer(new CPathProvider());
        fLogInConsumer = new CLogInConsumer();
        new CServer(fPhotoConsumer, fLogInConsumer);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            new Thread(new Main(), "Main-Thread").start();
        } catch (IOException | URISyntaxException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        CPhoto nextPhoto = null;
        while (!Thread.interrupted()) {
            try {
                if (nextPhoto == null) {
                    nextPhoto = fPhotoConsumer.getNextPhoto();
                }
                Connection connection = fLogInConsumer.getNextUser(nextPhoto.getUser());
                if (connection.isConnected()) {
                    Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Process file: " + nextPhoto + " on Connection: " + connection);
                    new CSendActivity(nextPhoto, connection).start();
                    nextPhoto = null;
                } else {
                    Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Connection problem: " + connection);
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
